<?php 
/*
*     无限极分类 类
*/
namespace Common\Library;
Class Category {
    //组合一维数组
    Static Public function unlimitedForLevel ($cate, $html = '', $pid = 0, $level = 0,$id_field='id',$pid_field="pid",$title_field='title') {
        $arr = array();
        foreach ($cate as $k => $v) {
            if ($v[$pid_field] == $pid) {
                $v['level'] = $level + 1;
                $v['html']  = $html;

                $arr[] = $v;
                $arr = array_merge($arr, self::unlimitedForLevel($cate, $html . $v[$title_field] . ' > ', $v[$id_field], $level + 1,$id_field,$pid_field));
            }
        }
        return $arr;
    }
    //组合多维数组
    Static Public function unlimitedForLayer ($cate, $name = 'child', $pid = 0,$id_field='id',$pid_field="pid") {
        $arr = array();
        foreach ($cate as $v) {
            if ($v[$pid_field] == $pid) {
                $v[$name] = self::unlimitedForLayer($cate, $name, $v[$id_field],$id_field,$pid_field);
                $arr[] = $v;
            }
        }
        return $arr;
    }
    //传递一个子分类ID返回所有的父级分类  
    Static Public function getParents ($cate, $id,$id_field='id',$pid_field="pid") {
        $arr = array();
        foreach ($cate as $v) {
            if ($v[$id_field] == $id) {
                $arr[] = $v;
                $arr = array_merge(self::getParents($cate, $v[$pid_field],$id_field,$pid_field), $arr); 
            }
        }
        return $arr;
    }
    //传递一个子分类ID返回所有的父级分类ID 
    Static Public function getParentsId ($cate, $id,$id_field='id',$pid_field="pid") {
        $arr = array();
        foreach ($cate as $v) {
            if ($v[$id_field] == $id) {
                $arr[] = $v[$id_field];
                $arr = array_merge(self::getParentsId($cate, $v[$pid_field],$id_field,$pid_field), $arr); 
            }
        }
        return $arr;
    }
    //传递一个父级分类ID返回所有子分类ID
    Static Public function getChildsId ($cate, $pid,$id_field="id",$pid_field="pid") {
        $arr = array();
        foreach ($cate as $v) {
            if ($v[$pid_field] == $pid) {
                $arr[] = $v[$id_field];
                $arr = array_merge($arr, self::getChildsId($cate, $v[$id_field],$id_field,$pid_field));
            }
        }
        return $arr;
    }
    //传递一个父级分类ID返回所有子分类
    Static Public function getChilds ($cate, $pid,$id_field="id",$pid_field="pid") {
        $arr = array();
        foreach ($cate as $v) {
            if ($v[$pid_field] == $pid) {
                $arr[] = $v;
                $arr = array_merge($arr, self::getChilds($cate, $v[$id_field],$id_field,$pid_field));
            }
        }
        return $arr;
    }

}